<?php

namespace App\Dao\Sign;

use App\Model\User\UserBill;
use Yj\Constants\Annotation\Type;
use Yj\Daos\BaseDaos;
use App\Model\Sign\SignTask;
use Hyperf\Database\Model\Builder;
use Yj\Daos\Verify;
use Hyperf\Utils\Collection;

/**
 * @var SignTask
 * @method $this params($params)
 */
class SignTaskDao extends BaseDaos
{
    public function searchParams(Collection $params)
    {
        $search = $this->getSearch();
        $params->check('id', function ($id) use ($search) {
            $search->where('id', $id);
        });
        $params->check('status', function ($status) use ($search) {
            $search->where('status', $status);
        });
        return $search;
    }

    public function lists(Collection $params)
    {
        $data = $this->params($params)->orderByDesc("id")->getList();
        return $data;
    }

    public function add(Collection $params)
    {
        $data = $this->create($params->toArray());
        return $data;
    }

    public function edit(int $id, Collection $params)
    {
        $data = $this->params(_Collect(["id" => $id]))->firstOrError();
        $data->fill($params->toArray());
        return $data->save();
    }

    public function del(int $id)
    {
        $data = $this->params(_Collect(["id" => $id]))->firstOrError();
        return $data->delete();
    }

    public function isReceive(mixed $user_id, $code)
    {
        /** @var UserBill $userBillModel */
        $userBillModel = App(UserBill::class);
        return $userBillModel->lockForUpdate()->where('uid', $user_id)->where('link_id', $code)
            ->tap(function ($query) use ($code) {
                if (\App\Constants\SignTask::getValue($code, Type::class) == 0) {
                    $query->yjRangeTime('add_time', 'day');
                }
            })
            ->exists();
    }

    public function setField(int $id, string $field, int $value)
    {
        $data = $this->where('id', $id)->firstOrError();
        $update = [$field => $value];

        $data->fill($update);
        return $data->save();
    }
}
